package cn.edu.nwafu.hjpg.controller;


import cn.edu.nwafu.hjpg.common.HttpResult;
import cn.edu.nwafu.hjpg.entity.Element;
import cn.edu.nwafu.hjpg.service.ElementService;

import org.springframework.data.domain.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/element")
public class ElementController {
    final ElementService elementService;

    public ElementController(ElementService elementService) {
        this.elementService = elementService;
    }


    /**
     * 根据一个或者多个属性分页查询
     *
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @GetMapping(value = "/")
    @ResponseBody
    public HttpResult queryElemByPage(@RequestParam(value = "type", defaultValue = "all") String type, @RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
                                   @RequestParam(value = "pageSize", defaultValue = "20") int pageSize, @RequestParam(value = "keyword", defaultValue = "", required = false) String keyword) {

        Pageable pageable = PageRequest.of(pageNumber - 1, pageSize);
        return HttpResult.ok(elementService.findByType(type,keyword, pageable));
    }

    @PostMapping(value = "/")
    @ResponseBody
    public HttpResult addElement(@RequestBody Element element) {
        return HttpResult.ok(elementService.addElement(element));
    }

    @GetMapping(value = "/{id}")
    @ResponseBody
    public HttpResult get(@PathVariable("id") String id) {
        return HttpResult.ok(elementService.findById(id));
    }

    @PostMapping("/updateElement")
    @ResponseBody
    public HttpResult updateElement(@RequestBody Element element) {

        return HttpResult.ok(elementService.updateElement(element));
    }

    @DeleteMapping("/{id}")
    @ResponseBody
    public HttpResult delElement(Element element) {

        elementService.delElement(element);
        return HttpResult.ok();
    }

    @RequestMapping(value = "/information",method = RequestMethod.POST)
    @ResponseBody
    public HttpResult findElementByCasNo(@RequestParam() String casNo){
        List<Element> elementList = elementService.findAllByCasNo(casNo);
        if(elementList.size()>0){
            return HttpResult.ok(elementList.get(0));
        }
        else{
            System.out.println("elementList.size()"+elementList.size());
            Element element = new Element();
            element.setLhsxbBhzqy("找不到数据");
            element.setLhsxbSrjd("找不到数据");
            return HttpResult.ok(element);
        }
    };


}
